/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.academy.web.action.course;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.model.Resolution;
import ar.uba.fi.posgrado.academy.model.Subject;
import ar.uba.fi.posgrado.academy.service.BodyService;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.academy.service.SubjectService;
import ar.uba.fi.posgrado.academy.web.form.course.CourseForm;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.util.CommonUtils;

/**
 * Action que modifica un {@link Course curso}.<br>
 * 
 * @author ariel.piechotka
 */
public class ModifyCourseAction extends Action {
	/** Logger */
	private static Logger logger = Logger.getLogger(ModifyCourseAction.class);

	private CourseService courseService;

	private BodyService bodyService;

	private SubjectService subjectService;

	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	public void setBodyService(BodyService bodyService) {
		this.bodyService = bodyService;
	}

	public void setSubjectService(SubjectService subjectService) {
		this.subjectService = subjectService;
	}

	/**
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Por modificar un curso ...");
		}

		CourseForm form = (CourseForm) actionForm;
		Long id = new Long(request.getParameter("id"));
		String code = request.getParameter("code");
		String name = request.getParameter("name");
		String curriculum = request.getParameter("curriculum");
		String certificate = request.getParameter("certificate");
		Long courseTypeId = Long.parseLong(request.getParameter("courseType"));
		Long bodyId = Long.parseLong(request.getParameter("idBody"));
		String firstDueDate = request.getParameter("firstDueDate");
		
		List<Long> subjectIds = form.getChosenSubjectsAsList();
		Set<Subject> subjects = new HashSet<Subject>();
		for (Long subjectId : subjectIds)
			subjects.add(subjectService.getById(subjectId));

		Course course = courseService.getById(id);
		course.setCode(code);
		course.setName(name);
		course.setCurriculum(curriculum);
		course.setCertificate(certificate);
		course.setCourseType(courseService.getCourseTypeById(courseTypeId));
		course.setBody(bodyService.getById(bodyId));
		course.setSubjects(subjects);
		course.setFirstDueDate(CommonUtils.toDateFromStringStandard(firstDueDate));

		Set<Resolution> resolutions = course.getResolutions();
		resolutions.removeAll(resolutions);
		String resolutionsStr = request.getParameter("resolutionsAsList");
		if (!resolutionsStr.trim().equals(""))
			for (String resolutionParamsStr : resolutionsStr.split(";")) {
				String[] resolutionParams = resolutionParamsStr.split(",", 2);
				tryAddResolution(resolutions, resolutionParams[0],
						resolutionParams[1], course);
			}
		tryAddResolution(resolutions, request.getParameter("resolution"),
				request.getParameter("fileNumber"), course);

		try {
			course = courseService.update(course);
		} catch (RepeatedNameException e) {
			logger.info(e.getMessage());
			ActionMessages errors = new ActionMessages();
			errors.add("course.code", new ActionMessage(e.getMessage(), false));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
		logger.info("Modificar curso finalizado");
		return mapping.findForward("success");
	}

	private void tryAddResolution(Set<Resolution> resolutions,
			String resolutionNumber, String fileNumber, Course course) {
		if (!resolutionNumber.trim().equals("")
				|| !fileNumber.trim().equals("")) {
			Resolution resolution = new Resolution();
			resolution.setResolutionNumber(resolutionNumber);
			resolution.setFileNumber(fileNumber);
			resolution.setCourse(course);
			resolutions.add(resolution);
		}
	}
}
